package com.zjlanyun.erp.interior.production;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aihook.alertview.library.AlertView;
import com.aihook.alertview.library.OnItemClickListener;
import com.aihook.wheelpickerview.library.TimePickerView;
import com.alibaba.fastjson.JSON;
import com.yolanda.nohttp.rest.Response;
import com.zjlanyun.erp.Data;
import com.zjlanyun.erp.R;
import com.zjlanyun.erp.config.AppConfig;
import com.zjlanyun.erp.interior.CommonList;
import com.zjlanyun.erp.network.WebApi;
import com.zjlanyun.erp.nohttp.HttpRequest;
import com.zjlanyun.erp.nohttp.SimpleHttpListener;
import com.zjlanyun.erp.rfid.m10.u8.activity.OutPowerActivity;
import com.zjlanyun.erp.utils.Toastor;
import com.zjlanyun.erp.utils.ViewUtil;
import com.zjlanyun.erp.view.BaseRFIDActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.OnClick;
//换班，下机
public class Unloading extends BaseRFIDActivity {

    @Bind(R.id.et_FQty) EditText et_FQty;
    @Bind(R.id.et_Fjitaiqty) EditText et_Fjitaiqty;
    @Bind(R.id.et_FCipinqty) EditText et_FCipinqty;
    @Bind(R.id.et_FTuicangqty) EditText et_FTuicangqty;
    @Bind(R.id.et_Fjietou) EditText et_Fjietou;
    @Bind(R.id.et_FZhongLiang) EditText et_FZhongLiang;
    @Bind(R.id.tv_result) TextView tv_result;
    @Bind(R.id.tv_epc) TextView tv_epc;
    @Bind(R.id.tv_FGongxuName) TextView tv_FGongxuName;
    @Bind(R.id.tv_status) TextView tv_status;
    @Bind(R.id.tv_FName) TextView tv_FName;
    @Bind(R.id.tv_FBillDate) TextView tv_FBillDate;
    @Bind(R.id.tv_FCLName) TextView tv_FCLName;
    @Bind(R.id.tv_FCLNumber) TextView tv_FCLNumber;
    @Bind(R.id.tv_FNumber) TextView tv_FNumber;
    @Bind(R.id.tv_FModel) TextView tv_FModel;
    @Bind(R.id.tv_FBatchNO) TextView tv_FBatchNO;
    @Bind(R.id.ll_submit) LinearLayout ll_submit;
    @Bind(R.id.et_FMacSpeed) EditText et_FMacSpeed;
    @Bind(R.id.et_FNote) EditText et_FNote;
    @Bind(R.id.btn_selectbanci) Button btn_selectbanci;
    @Bind(R.id.btn_FCPLevel) Button btn_FCPLevel;
    @Bind(R.id.btn_time) Button btn_time;
    @Bind(R.id.tv_FPlanBegDate) TextView tv_FPlanBegDate;

    private boolean scaning = false;
    private String apiUrl = "";
    private ArrayList<HashMap<String, Object>> mBanciList; //班次
    private String FWorkShift = ""; //班次
    private ArrayList<HashMap<String, Object>> mFCPLevelList; //标识
    private String FCPLevel = ""; //标识
    private boolean isUnloading = false; //是否下机
    private String Flag = ""; //huanban换班、xiaji下机

    public static final int REQUESTCODE_BANCI = 1;
    public static final int REQUESTCODE_BIAOSHI = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.unloading);
        initBaseView();
        initView();
    }

    private void initView() {
        apiUrl = WebApi.production();
        Bundle bundle = getIntent().getExtras();
        if (bundle.getString("title").equals("换班")) {
//            btn_FCPLevel.setVisibility(View.GONE);
            Flag = "huanban";
        } else {
            isUnloading = true;
            Flag = "xiaji";
        }
        title.setText(bundle.getString("title"));
        ll_submit.setVisibility(View.VISIBLE);
        //初始化班次
        if (!AppConfig.getInstance().getString("FWorkShift", "").equals("")) {
            FWorkShift = AppConfig.getInstance().getString("FWorkShift", "");
            btn_selectbanci.setText(FWorkShift);
        }
        ll_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!tv_epc.getText().toString().equals("")) {
                    new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {
                            if (position == 0) {
                                finish();
                            }
                        }
                    }).show();
                } else {
                    finish();
                }
            }
        });

        btn_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerView(mContext, TimePickerView.Type.ALL);
                //控制时间范围
                //        Calendar calendar = Calendar.getInstance();
                //        pvTime.setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR));
                pvTime.setTime(new Date());
                pvTime.setCyclic(false);
                pvTime.setCancelable(true);
                //时间选择后回调
                pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

                    @Override
                    public void onTimeSelect(Date date) {
//                        tvTime.setText(getTime(date));
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        tv_FBillDate.setText(sdf.format(date));
                    }
                });
                pvTime.setTextSize(16);
                //弹出时间选择器
                pvTime.show();
            }
        });
    }

    /**
     * 开始扫描
     */
    public void startScan() {
        tv_status.setText("盘询开始");
        scanNumber = 1;
        scaning = true;
        super.startScan();
    }

    /**
     * 停止扫描
     */
    public void stopScan() {
        tv_status.setText("盘询结束");
        scaning = false;
        super.stopScan();
    }

    public void refreshText() {
        super.refreshText();
        tv_result.setText(String.format("扫描到:%d个", m_curInventoryBuffer.lsTagList.size()));
        if (m_curInventoryBuffer.lsTagList.size() > 0) {
            getUnloadingInfo(m_curInventoryBuffer.lsTagList.get(0).getStrEPC().replace(" ", ""));
        }
    }

    /**
     * 获取换班、下机信息
     */
    private void getUnloadingInfo(String epc) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("epc", epc);
        param.put("FGongXuNO", "104");
        param.put("FActionFlag", Flag);
        HttpRequest client = new HttpRequest(mContext, apiUrl, "getUnloadingInfo", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                JSONObject data = response.get().optJSONObject("data");
                tv_epc.setText(data.optString("epc"));
                tv_FName.setText(data.optString("FName"));
                tv_FBillDate.setText(data.optString("FBillDate"));
                tv_FCLName.setText(data.optString("FCLName"));
                tv_FNumber.setText(data.optString("FNumber"));
                tv_FCLNumber.setText(data.optString("FCLNumber"));
                tv_FModel.setText(data.optString("FModel"));
                tv_FBatchNO.setText(data.optString("FBatchNO"));
                et_FMacSpeed.setText(data.optString("FMacSpeed"));
                tv_FPlanBegDate.setText(data.optString("FPlanBegDate"));
                tv_FGongxuName.setText(data.optString("FGongxuName"));

                mBanciList = new ArrayList<>();
                JSONArray banci = data.optJSONArray("banci");
                for (int i = 0; i < banci.length(); i++) {
                    JSONObject item = banci.optJSONObject(i);
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("FName", item.optString("FName"));
                    mBanciList.add(map);
                }

                mFCPLevelList = new ArrayList<>();
                JSONArray biaoshi = data.optJSONArray("biaoshi");
                for (int i = 0; i < biaoshi.length(); i++) {
                    JSONObject item = biaoshi.optJSONObject(i);
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("FName", item.optString("FName"));
                    mFCPLevelList.add(map);
                }

                if (data.optString("FCurrentGongXuNO").equals("104") && isUnloading) {
                    Toastor.getInstance().showShortToast("该产品已下机");
                }
            }

            @Override
            public void onError(int what, Response<JSONObject> response) {
                clear();
                super.onError(what, response);
            }
        });
    }

    @OnClick(R.id.btn_FCPLevel)
    public void select_biaoshi() {
        if (mFCPLevelList != null) {
            Bundle bundle = new Bundle();
            bundle.putString("title", "选择产品标识");
            bundle.putIntArray("layout", new int[]{R.id.tv1});
            bundle.putStringArray("field", new String[]{"FName"});
            bundle.putString("list", JSON.toJSONString(mFCPLevelList));
            bundle.putString("action", "common");
            Intent intent = new Intent(Unloading.this, CommonList.class);
            intent.putExtras(bundle);
            startActivityForResult(intent, REQUESTCODE_BIAOSHI);
        } else {
            Toastor.getInstance().showShortToast("无标识数据，请先扫卡");
        }
    }

    /**
     * 选择班次
     */
    @OnClick(R.id.btn_selectbanci)
    public void select_banci() {
        if (mBanciList != null) {
            Bundle bundle = new Bundle();
            bundle.putString("title", "选择班次");
            bundle.putIntArray("layout", new int[]{R.id.tv1});
            bundle.putStringArray("field", new String[]{"FName"});
            bundle.putString("list", JSON.toJSONString(mBanciList));
            bundle.putString("action", "common");
            Intent intent = new Intent(Unloading.this, CommonList.class);
            intent.putExtras(bundle);
            startActivityForResult(intent, REQUESTCODE_BANCI);
        } else {
            Toastor.getInstance().showShortToast("无班次数据，请先扫卡");
        }
    }

    /**
     * 提交
     */
    @OnClick(R.id.ll_submit)
    public void postUnloading() {
        ViewUtil.hideInputMethod(mContext, ll_back);
        if (tv_epc.getText().toString().equals("")) {
            Toastor.getInstance().showShortToast("请先扫卡");
            return;
        } else if (et_FQty.getText().toString().equals("")) {
            Toastor.getInstance().showShortToast("请输入完成米数");
            return;
        } else if (FWorkShift.equals("")) {
            Toastor.getInstance().showShortToast("请选择班次");
            return;
        }
//        } else if (isUnloading && FCPLevel.equals("")) {
//            Toastor.getInstance().showShortToast("请选择产品标识");
//            return;
//        }

        HashMap<String, Object> param = new HashMap<>();
        param.put("epc", tv_epc.getText().toString());
        param.put("FQty", et_FQty.getText().toString());
        param.put("Fjitaiqty", et_Fjitaiqty.getText().toString().equals("")?0:et_Fjitaiqty.getText().toString());
        param.put("FCipinqty", et_FCipinqty.getText().toString().equals("")?0:et_FCipinqty.getText().toString());
        param.put("FTuicangqty", et_FTuicangqty.getText().toString().equals("")?0:et_FTuicangqty.getText().toString());
        param.put("Fjietou", et_Fjietou.getText().toString().equals("")?0:et_Fjietou.getText().toString());
        param.put("FZhongliang", et_FZhongLiang.getText().toString().equals("")?0:et_FZhongLiang.getText().toString());
        param.put("FBillDate", tv_FBillDate.getText().toString());
        param.put("FNote", et_FNote.getText().toString());
        param.put("FWorkShift", FWorkShift);
//        param.put("FCPLevel", FCPLevel);
        param.put("FMacSpeed", et_FMacSpeed.getText().toString());
        param.put("Flag", Flag);
        param.put("FGongXuNO", "104");
        param.put("FActionFlag", Flag);
        HttpRequest client = new HttpRequest(mContext, apiUrl, "postUnloading", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                clear();
                AppConfig.getInstance().putString("FWorkShift", FWorkShift);
                Toastor.getInstance().showShortToast(R.string.submit_success);
            }
        });
    }

    /**
     * 清空数据
     */
    private void clear() {
        tv_epc.setText("");
        et_FQty.setText("");
        tv_FCLName.setText("");
        tv_FName.setText("");
        tv_FNumber.setText("");
        tv_FCLNumber.setText("");
        tv_FModel.setText("");
        tv_FBillDate.setText("");
        et_FNote.setText("");
        tv_FBatchNO.setText("");
        et_FMacSpeed.setText("");
        et_Fjitaiqty.setText("");
        et_FCipinqty.setText("");
        et_FTuicangqty.setText("");
        et_Fjietou.setText("");
        et_FZhongLiang.setText("");
        tv_FPlanBegDate.setText("");
        tv_FGongxuName.setText("");
        btn_FCPLevel.setText("选择标识");
        FCPLevel = "";
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 80 && Build.MODEL.equals(Data.RFID_DEVICE)) {
            if (scaning) {
                stopScan();
            } else {
                startScan();
            }
        } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (!tv_epc.getText().toString().equals("")) {
                new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            finish();
                        }
                    }
                }).show();
                return false;
            }
        } else if ((keyCode == 131 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 132 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 133 && Build.MODEL.equals(Data.RFID_DEVICE))) {
            Intent intent = new Intent(mContext, OutPowerActivity.class);
            intent.putExtra("from", "RFID" + className);
            startActivity(intent);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTCODE_BANCI && resultCode == RESULT_OK && data != null) {
            Bundle bundle = data.getExtras();
            int p = bundle.getInt("position");
            btn_selectbanci.setText(mBanciList.get(p).get("FName").toString());
            FWorkShift = mBanciList.get(p).get("FName").toString();
        } else if (requestCode == REQUESTCODE_BIAOSHI && resultCode == RESULT_OK && data != null) {
            Bundle bundle = data.getExtras();
            int p = bundle.getInt("position");
            btn_FCPLevel.setText(mFCPLevelList.get(p).get("FName").toString());
            FCPLevel = mFCPLevelList.get(p).get("FName").toString();
        }
    }
}
